#!/usr/bin/python

# Authors:  
# Otavio Sturm 
# Vinicius Arcanjo 

import noise
import numpy
import math
import random
import matplotlib.pyplot as plt

def plotVec(vec,title):
	plt.plot(vec)
	plt.title(str(title))
	plt.savefig(str(title)+".png", bbox_inches=0)
	plt.close()

#vec : input signal.
#iterations : quantity of iterations.
#iterationsPlot : iterations indexes that is gonna  be ploted
#averageWindow : quantity of elements used to compute the mean value.
def movingAverage(vec, iterations, iterationsPlotIndexDivisor, averageWindow):
	
	for x in range(iterations):
		# interval: [0,len(vec)-averageWindow+1)
		for i in range(len(vec)-averageWindow+1):
			sum = 0
			#interval: [0, averageWindow)
			for j in range(averageWindow):
				sum += vec[i+j]
				#print str(vec[i+j]) + " "
			#print
			vec[i] = sum/averageWindow
		
		#discard lost points
		vec = vec[0:len(vec)-averageWindow+1]
		
		if x%iterationsPlotIndexDivisor == 0:
			plotVec(vec,"iteration " + str(x))	
		
	return vec

def main():

	######################## FIXED PARAMETERS ################################
	
	#################### INPUT + NOISE SIGNAL PARAMETERS #####################
	
	samples = 2000
	mean = 0
	amplitude = 10 
		
	inputSignal = [0] * samples
	resVec = [0] * samples
	
	noisyVec = noise.generateNoisyVector(mean, amplitude, samples)
	#noisyVec = [0] * samples
	
	################### MOVING AVERAGE PARAMETERS ############################
	
	iterations = 500
	averageWindow = 2 
	# this divisor is used to snapshot at specific indexes. For example, if iterations = 100, and iteratoinsPlotIndexDivisor = 10. So, at index 0, 10, 20, 30, .., 90 an screenshot will be taken.
	iterationsPlotIndexDivisor = 90.0
	
	######################## END FIXED PARAMETERS ############################
	
	######################## INPUT SIGNAL ###################################
	# signal input as a sine wave
	for i in range(len(inputSignal)):
		inputSignal[i] = (amplitude/2.0)*math.sin(math.radians(i))
	
	# plot (4/3.1415)*(sin(2*3.1415*1000*x) + 0.333*(sin(6*3.1415*1000*x)) + 0.2*(sin(10*3.1415*1000*x)))
	# signal inptu as a squared wave fourier's transform
	for i in range(len(inputSignal)):
		inputSignal[i] = (amplitude/2.0)*(4.0/3.1415)*(math.sin(i*2*3.1415*100)+ 0.333*math.sin(i*6*3.1415*100) + 0.2*math.sin(i*10*3.1415*100))
	
	# sum noisy + input together in one signal.
	for i in range(len(inputSignal)):
		resVec[i] = noisyVec[i] + inputSignal[i]
	
	plotVec(inputSignal,"inputSignal")
	plotVec(noisyVec,"noiseSignal")
	plotVec(resVec,"inputSignal+noiseSignal")
	
	###################### END INPUT SIGNAL ################################
	
	movingAverage(resVec,iterations, iterationsPlotIndexDivisor, averageWindow)

main()
